package com.cqhfan.core.utils;

import cn.hutool.crypto.asymmetric.RSA;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtil {

    public static String createToken(Map<String, Object> map, String privateKey, long dateOffset) {
        RSA rsa = new RSA(privateKey, null);
        Map<String, Object> header = new HashMap<>();
        header.put("type", "jwt");
        header.put("author", "schandfanfan");
        header.put("alg", SignatureAlgorithm.RS256.getValue());
        return Jwts.builder()
                .setHeader(header)
                .signWith(rsa.getPrivateKey(), SignatureAlgorithm.RS256)
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * dateOffset))
                .compact();
    }

    public static Claims parseToken(String token, String publicKey) {
        RSA rsa = new RSA(null, publicKey);
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(rsa.getPublicKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("非法token：{}", token);
            return null;
        }
    }
}
